import time
import asyncio
import redis
import redis.asyncio as aioredis  # 官方支持的异步 Redis 客户端

TOTAL = 1000  # 写入次数

# 同步写入 Redis
def sync_write_redis():
    r = redis.StrictRedis(host='localhost', port=6379, decode_responses=True)
    
    start = time.time()
    for i in range(TOTAL):
        # 同步写入，key 前缀 user1:
        r.set(f"user1:{i}", f"value{i}")
    print(f"[同步] 总耗时：{round(time.time() - start, 2)} 秒")

# 异步写入 Redis
async def async_write_redis():
    r = aioredis.Redis(host='localhost', port=6379, decode_responses=True)

    start = time.time()
    tasks = []
    for i in range(TOTAL):
        # 异步写入，key 前缀 user2:
        tasks.append(r.set(f"user2:{i}", f"value{i}"))
    await asyncio.gather(*tasks)
    print(f"[异步] 总耗时：{round(time.time() - start, 2)} 秒")

    await r.aclose()

if __name__ == "__main__":
    print("开始测试 Redis 同步写入")
    sync_write_redis()

    print("\n开始测试 Redis 异步写入")
    asyncio.run(async_write_redis())
